//
//  TopicDetailViewController.m
//  yilutongxing
//
//  Created by ios-23 on 17/4/8.
//  Copyright © 2017年 YZE. All rights reserved.
//
#import "MJRefresh+FooterManger.h"
#import "TopicDetailViewController.h"
#import "TopicDetailView.h"
#import "TopicDetailTableViewCell.h"
#import "RPUserInfoBean.h"
#import <MJExtension.h>

#define CommentURL @"/api/comment_topic/"
#define AddURL @"/api/comment_topic/1?page="
#define ReplyCommentURL @"/api/comments"
#define DeleteTopicURL @"/api/topics/"
#define URL_DeleteComment @"/api/comments"
#define URL_Favoriate @"/api/lore-collections"

#define TopicID (self.topicDetail.ID?self.topicDetail.ID:self.topicDetailDic[@"id"])

@interface TopicDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,TopicDetailTableViewCellDelegate,TopicDetailViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *editorView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *roundStyleTextField;
@property (strong, nonatomic) IBOutlet UIButton *btn_send_comment;
@property (nonatomic,assign) CGFloat height;
@property (nonatomic,strong)RPUserInfoBean *userInfo;
@property (nonatomic,strong)NSMutableArray *userInfoArr;
@property (nonatomic,strong)NSArray *addDataArr;

@property (nonatomic,assign)CGFloat cellHeight;
@property (nonatomic,assign)NSInteger pagNum;

@property (nonatomic,copy)NSString* tag;
@end
@implementation TopicDetailViewController

-(void)setFrame{
    self.editorView.frame =CGRectMake(self.editorView.frame.origin.x, [UIScreen mainScreen].bounds.size.height-104, [UIScreen mainScreen].bounds.size.width, self.editorView.frame.size.height);
    self.roundStyleTextField.frame = CGRectMake(20, 7, self.editorView.frame.size.width-40, self.editorView.frame.size.height-14);
    self.roundStyleTextField.layer.cornerRadius = 10;
    self.roundStyleTextField.layer.masksToBounds = YES;
    self.roundStyleTextField.returnKeyType = UIReturnKeySend;
    self.roundStyleTextField.delegate = self;
    self.roundStyleTextField.inputAccessoryView = [UIView new];
    self.tableView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-self.editorView.frame.size.height-64);
    [self addTapOnTableView];
    UIImage *leftImage=[[UIImage imageNamed:@"返回"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *leftButtonItem=[[UIBarButtonItem alloc]initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem=leftButtonItem;
    
    [self.btn_send_comment addTarget:self action:@selector(sendComment) forControlEvents:UIControlEventTouchUpInside];
}
-(void)addTapOnTableView{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenKeyBoard)];
    [self.tableView addGestureRecognizer:tap];
}
-(void)hiddenKeyBoard{
    [self.view endEditing:YES];
}
#pragma TopicDetailViewDelegate
-(void)deleteTopicAction{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"请选择操作" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"收藏" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        [data setValue:TopicID forKey:@"topicId"];
        [[YZENetwork sharedInstace] postRequestWithUrl:[NSString stringWithFormat:@"%@%@",BASE,URL_Favoriate] parameters:data delegate:self requestTag:3 successBlock:^(id responseObject) {
            [UIView showToastWindowWithMessage:@"收藏成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }];
    UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:yesAction];
    [alert addAction:noAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma TopicDetailTableViewCellDelegate
-(void)commentWithButtonTag:(NSInteger)tag{
    [self.roundStyleTextField becomeFirstResponder];
    RPUserInfoBean *base=self.userInfoArr[tag];
    self.roundStyleTextField.placeholder=[NSString stringWithFormat:@"回复%@:",base.user.firstName];

    self.tag = [NSString stringWithFormat:@"%ld",(long)tag];
}
-(void)jumpToUserInformaintionWithButtonTag:(NSInteger)tag{
     NSLog(@"跳转到用户信息");
}
-(void)deleteWithButtonTag:(NSInteger)tag{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"确定删除这条评论吗？" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        RPUserInfoBean *base = self.userInfoArr[tag];
        [[YZENetwork sharedInstace] deleteRequestWithUrl:[NSString stringWithFormat:@"%@%@/%lld",BASE,URL_DeleteComment, [base.ID longLongValue]] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
            [UIView showToastWindowWithMessage:@"已删除"];
            [self.navigationController popViewControllerAnimated:YES];
            [self.userInfoArr removeObjectAtIndex:tag];
            [self.tableView reloadData];
        }];
    }];
    UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:yesAction];
    [alert addAction:noAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma 评论
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self sendComment];
    return YES;
}
-(void)sendBtnClicked{
    [self sendComment];
}
-(void)sendComment{
    [self.view endEditing:YES];
    if (self.roundStyleTextField.text.length >0) {
        if (self.tag) {
            RPUserInfoBean *base=self.userInfoArr[[self.tag integerValue]];
            NSDictionary *dataDic = @{@"commentId":base.ID,@"replyerId":base.user.ID};
            [self editingCommentWithId:dataDic];
        }else{
            [self editingCommentWithId:nil];
        }
    }else{
        [UIView showToastWindowWithMessage:@"评论内容不能为空"];
    }
}
-(void)editingCommentWithId:(NSDictionary*)data{
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    if (data) {
        NSString *replyId = data[@"replyerId"];
        dataDic = [@{@"content":self.roundStyleTextField.text,@"replyId":replyId,@"topicId":TopicID} mutableCopy];
    }else{
        dataDic = [@{@"content":self.roundStyleTextField.text,@"topicId":TopicID} mutableCopy];
    }
    
    [[YZENetwork sharedInstace] postRequestWithUrl:[NSString stringWithFormat:@"%@%@?%@",BASE,ReplyCommentURL,PLATFORM] parameters:dataDic delegate:self requestTag:1 successBlock:^(id responseObject) {
        self.roundStyleTextField.text = @"";
        [self loadDataAction];
    }];
}


-(void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)collection{
    NSLog(@"收藏");
    NSString *tId = TopicID;
     NSLog(@"TopicID  = = =%@",tId);
    
    NSDictionary *dic2=@{@"topicId":TopicID};
    [[YZENetwork sharedInstace]postRequestWithUrl:[BASE stringByAppendingString:URL_Favoriate] parameters:dic2 delegate:self requestTag:1 successBlock:^(id responseObject) {
        [UIView showToastWindowWithMessage:@"收藏成功"];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSDictionary *dic=[UserDefaultsTools getUserDefaultsForKey:USERINFO_KEY];
    self.userInfo=[RPUserInfoBean mj_objectWithKeyValues:dic];
    
    self.title=(self.topicDetail.name?self.topicDetail.name:self.topicDetailDic[@"name"]);
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationbarBackGroundImage"] forBarMetrics:UIBarMetricsDefault];
    
    [self setFrame];
    
    //self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"收藏" style:UIBarButtonItemStylePlain target:self action:@selector(collection)];
    
    [self setTableViewWithTopicDetailView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"TopicDetailTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"commentCell"];
    self.tableView.tableFooterView = [UIView new];
    
    [self loadDataAction];
    
    [self initRefersh];
}
-(void)loadDataAction{
    [[YZENetwork sharedInstace] getRequestWithUrl:[NSString stringWithFormat:@"%@%@%@",BASE,CommentURL,TopicID] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
        self.userInfoArr= [RPUserInfoBean mj_objectArrayWithKeyValuesArrayAdd:responseObject];
        [self.tableView reloadData];
    }];
}
-(void)setTableViewWithTopicDetailView{
    TopicDetailView *detailView=[[NSBundle mainBundle]loadNibNamed:@"TopicDetailView" owner:nil options:0].firstObject;
    if (self.topicDetailDic) {
        [detailView showDataWithDictionry:self.topicDetailDic];
    }else{
        detailView.data=self.topicDetail;
    }
    //设置代理
    detailView.delegate = self;
    [detailView setTopicDetailViewFrame:^(CGFloat height) {
        if (self.topicDetail.imagesHeight>0) {
            self.height = height+self.topicDetail.imagesHeight+16;
            
        }else{
            self.height = height;
        }
    }];
    detailView.frame=CGRectMake(0, 0, SCREEN_WIDTH, self.height);
    self.tableView.tableHeaderView=detailView;
}

-(void)initRefersh{
    __block TopicDetailViewController *TopicVC = self;
    self.tableView.mj_header=[RefershHelper headerWithRefreshingBlock:^{
        [self loadDataAction];
        NSLog(@"下拉刷新");
        [self.tableView.mj_header endRefreshing];
    }];
    self.pagNum = 0;
    self.tableView.mj_footer=[RefershHelper footerWithRefreshingBlock:^{
        TopicVC.pagNum++;
        NSLog(@"上拉加载，第%ld页", (long)TopicVC.pagNum);
        [[YZENetwork sharedInstace] getRequestWithUrl:[NSString stringWithFormat:@"%@%@%ld",BASE,AddURL,(long)TopicVC.pagNum] parameters:nil delegate:self requestTag:1 successBlock:^(id responseObject) {
            if (!responseObject || ((NSArray*)responseObject).count==0) {
                self.tableView.footRefreshState = MJFooterRefreshStateNoMore;
            }
            self.addDataArr= [RPUserInfoBean mj_objectArrayWithKeyValuesArrayAdd:responseObject];
            [self.userInfoArr addObjectsFromArray:self.addDataArr];
            [self.tableView reloadData];
            
        }];
        
        self.tableView.footRefreshState = MJFooterRefreshStateLoadMore;
    }];
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return 1;
        case 1:
            return self.userInfoArr.count;
        default:
            return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        UITableViewCell *fristCell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
            if (fristCell==nil) {
                fristCell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
            }
        fristCell.textLabel.text = @"评论";
        fristCell.textLabel.font = [UIFont systemFontOfSize:13];
        fristCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return fristCell;
    }else{
        
        TopicDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell" forIndexPath:indexPath];
        
        cell.delegate = self;
        
        RPUserInfoBean *base=self.userInfoArr[indexPath.row];
        cell.commentBtn.tag = indexPath.row;
        cell.deletTopicBtn.tag = indexPath.row;
        [cell showDataWithUser:base AndReply:base.reply isMine:[base.user.ID isEqualToString:self.userInfo.user.ID]];
        self.cellHeight = cell.height;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==1) {
        return 0.1;
    }else{
    return 15;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0 && indexPath.row==0) {
        return 30;
    }else{
        return self.cellHeight;
    }
}

@end
